#!/bin/bash

source ~/.bashrc

ES_URL="http://ip:9200"
username='elastic'
password='xxx'
enable_security=true

if [ "${enable_security}" == "true" ];then
    conn="curl --user ${username}:${password}"
else
    conn="curl "
fi

# 删除日期结尾"2022-07-02"
delete_indices() {
    #text-2022-07-02
    index_name=$1
    # 20220702
    index_day=`echo $index_name | awk -F '-' '{print $2$3$4}'`
    #2022-10-10
    check_day=`date -d '-3 months' '+%F'`
    check_day_timestamp=`date -d $check_day '+%s'`
    index_day_timestamp=`date -d $index_day '+%s'`
    
    #echo "$index_name $index_day $check_day_timestamp $index_day_timestamp"
    if [ ${index_day_timestamp} -lt ${check_day_timestamp} ]; then
        sleep 2
        curl -s -XDELETE ${ES_URL}/$index_name
    fi
}

# 删除日期结尾"202301"
delete_indices_trends() {
    #trends_unit-202301
    index_name=$1
    #202301
    index_day=`echo $index_name | awk -F '-' '{print $2}'`
    #202210
    check_day=`date -d '-3 months' '+%Y%m'`
    if [ $index_day -lt $check_day ]; then
        sleep 2
        curl -s -XDELETE ${ES_URL}/$index_name
    fi
}



delete_log_time() {
    #log_service_instance_5_20240301
    index_name=$1
    #提取日期
    index_day=`echo $index_name | awk -F '_' '{print $NF}'`
    #计算保留时间
    check_day=`date -d '-7 days' '+%F'`
    check_day_timestamp=`date -d $check_day '+%s'`
    index_day_timestamp=`date -d $index_day '+%s'`
    if [ ${index_day_timestamp} -lt ${check_day_timestamp} ]; then
        echo "删除: " ${index_name}
        ${conn} -s -XDELETE ${ES_URL}/$index_name
    fi

}

${conn} -s -XGET ${ES_URL}/_cat/indices | awk -F " " '{print $3}' | grep -E '^aiops_breakcount_v2_instance_|^log_service_instance_5_|^log_redis_2_|^log_nginx_1_|^log_host_1_' | while read LINE
do
    sleep 1
    delete_log_time $LINE
done
#curl -s -XGET ${ES_URL}/_cat/indices | awk -F " " '{print $3}' | grep '^trends_unit-' | while read LINE
#do
#    delete_indices_trends $LINE
#done

#curl -s -XGET ${ES_URL}/_cat/indices | awk -F " " '{print $3}' | grep -E 'text-|dvl-|^unit-|str-' | while read LINE
#do
#    delete_indices $LINE
#done

